<template>
    <el-dialog :model-value="dialogVisible" :close-on-click-modal="true" :before-close="handleClose" title="关联外部数据源"
        append-to-body width="680px">
        <div style="margin-bottom: 20px">
            <el-button type="primary" @click="addTab(editableTabsValue)">
                新增数关联数据源
            </el-button>
        </div>
        <el-tabs v-model="editableTabsValue" type="card" class="demo-tabs" closable @tab-remove="removeTab"
            size="small">
            <el-tab-pane v-for="(itemTab, indexTab) in formData" :key="indexTab"
                :label="itemTab.matchCode || indexTab + 1" :name="indexTab + 1">

                <el-form ref="formRef" :rules="rules" label-width="150px" style="margin-top:20px">
                    <el-form-item label="外部数据源识别码">
                        <el-input v-model="itemTab.matchCode" style="width:100%" placeholder="请输入外部数据源识别码" />
                        <!-- <el-button type="primary" style="margin-left: 20px" @click="addList">新增</el-button> -->
                    </el-form-item>
                    <div class="el-box">
                        <div class="el-li" v-for="(item, index) in itemTab.fieldDataMappingVOList" :key="index">
                            <el-input v-model="item.attrCode" :placeholder="'字段' + (index + 1)" class="el-input-one"
                                :disabled="true" />
                            <div style="height:32px;line-height:32px;width:100px;">对应的字段为：</div>
                            <el-input v-model="item.mappedForm" placeholder="请输入请输入外部字段code" class="el-input-one"
                                @blur="vlidValue2(item.mappedForm, index, itemTab.fieldDataMappingVOList, indexTab)" />
                            <!-- <el-button type="danger" style="color: #fff" :icon="Delete"
                                @click="deleteMappingList(index, indexTab)">
                            </el-button> -->
                        </div>
                    </div>
                </el-form>
            </el-tab-pane>
        </el-tabs>

        <template #footer>
            <span class="dialog-footer">
                <el-button :loading="loading" type="primary" @click="submit()">确定</el-button>
                <el-button @click="handleClose">取消</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script  setup>
import { Delete } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import api from '@/api/index'
// eslint-disable-next-line no-unused-vars
const props = defineProps({
    dialogVisible: {
        type: Boolean,
        default: false
    },
    formData: {
        type: Array,
        default: []
    },
    oldData: {
        type: Object,
        default: () => { }
    },
    localName: {
        type: String,
        default: ''
    }
})


const emit = defineEmits(['on-submit', 'handleClose'])
const formRef = ref(null)
const form = ref({})

const editableTabsValue = ref(1)
const editableTabs = ref([])
const options = ref([])
const rules = reactive({
    matchCode: [
        {
            required: true,
            message: '请输入外部数据源识别码',
            trigger: 'blur'
        }
    ]
})
const addList = () => {
    const newObj = {
        attrCode: '',
        mappedForm: ''
    }
    form.value.mappingList.push(newObj)
}
const addTab = (targetName) => {
    console.log(props.oldData, 777)

    let data = JSON.parse(JSON.stringify(props.oldData))
    props.formData.push(data)
    editableTabsValue.value = props.formData.length
}
const removeTab = (tabIndex) => {
    console.log(tabIndex, 'tabIndex')
    ElMessageBox.confirm(
        '您确定要进行删除操作吗?',
        '温馨提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            let id = props.formData[tabIndex - 1].metaFieldRelationId
            if (id) {
                api.dataMaintenance.outDataDelete({ id }).then(res => {
                    ElMessage.success('操作成功')
                })
            }
            props.formData.splice(tabIndex - 1, 1)

            editableTabsValue.value = tabIndex - 1

        })


}
const deleteMappingList = (i, parIndex) => {
    props.formData[parIndex].fieldDataMappingVOList.splice(i, 1)
}
const loading = ref(false)
const handleClose = () => {
    //formRef.value.resetFields()
    emit('handleClose', false)
}
const submit = () => {
    if (!formRef) return
    let go = true
   
    props.formData.forEach(itemPar => {
        console.log(itemPar, 'itemPar')
        if (itemPar.fieldDataMappingVOList) {
            let allEmpty = false
          for (let i = 0; i < itemPar.fieldDataMappingVOList.length; i++) {
            console.log(itemPar.fieldDataMappingVOList[i], 'itemPar.fieldDataMappingVOList[i]')
            if (itemPar.fieldDataMappingVOList[i].mappedForm) {
              allEmpty = true
              break
            }
            }
            if (!allEmpty) {
                ElMessage.error('每条数据源至少添加一条映射')
                throw new Error('')
            }
        }
        if (itemPar.matchCode == '' || itemPar.matchCode == null) {
            ElMessage.error('外部数据源识别码不能为空')
            throw new Error('')
        }
    })

    if (go) {
        let newList = []
        let list = JSON.parse(JSON.stringify(props.formData))
        list.forEach(item => {
            item.fieldDataMappingVOList = item.fieldDataMappingVOList.filter(filItem => !['', null].includes(filItem.mappedForm))
            newList.push({
                localName: props.localName,
                matchCode: item.matchCode,
                sourceId: item.sourceId,
                mappingList: item.fieldDataMappingVOList
            })
        })
        console.log(newList)

        api.dataMaintenance.insertFieldTable(newList).then((res) => {
            ElMessage({
                type: 'success',
                message: '关联成功!'
            });
            emit('on-submit')
            handleClose()
        })

    }
}


const vlidValue2 = (data, i, list, parIndex) => {
    list.forEach((item, index) => {
        if (i !== index) {
            if (item.mappedForm != '' && item.mappedForm === data) {
                ElMessage({
                    type: 'error',
                    message: '对应字段不能重复!'
                });
                props.formData[parIndex].fieldDataMappingVOList[index].mappedForm = ''
            }
        }
    })
}


const searchData = () => {
    if (form.value.matchCode) {
        console.log(form.value.matchCode)
    }
}

</script>

<style lang="scss" scoped>
.dialog-footer {
    text-align: right;
}

.el-box {
    max-height: 400px;
    overflow: auto;
}

.el-li {
    display: flex;
    align-content: center;
    justify-content: space-between;
    margin-bottom: 18px;
}

.el-input-one {
    width: 200px;
}
</style>
